/**
 * 多个实例没有锁竞争
 */
public class SynchronizedExample5 {

    static int count = 0;

    // 定义一个锁对象
    Object locker = new Object();

    public void increment () {
        synchronized (locker) {
            count++;
        }
    }

    public int getCount() {
        return count;
    }

    public static void main(String[] args) {

        SynchronizedExample5 example1 = new SynchronizedExample5();
        SynchronizedExample5 example2 = new SynchronizedExample5();

        Thread thread1 = new Thread(() -> {
            for (int i = 0; i < 10000; i++) {
                example1.increment();
            }
        });
        Thread thread2 = new Thread(() -> {
            for (int i = 0; i < 10000; i++) {
                example2.increment();
            }
        });

        thread1.start();
        thread2.start();

        try {
            thread1.join();
            thread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(example1.getCount());
    }
}

// 18756
